package com.ar.studyapp;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.ar.adapter.ResultAdapter;
import com.ar.datahandler.ResultHolder;
import com.ar.datahandler.StringJSONHandler;
import com.ar.network.NetworkUtility;
import com.ar.network.OnResponseListener;
import com.ar.network.RequestBuilder;
import com.ar.network.SOAPConnector;

public class ResultActivity extends BaseActivity implements OnResponseListener{
	private TextView tvScore;
	private TextView tvRatio;
	private int[] userAnswers;
	private ArrayList<Integer> ansIDs;
	private GridView gridView;
	private ResultAdapter resultAdapter;
	private StringJSONHandler jsonHandler;
	private ResultHolder resultHolder;
	private ProgressDialog progressDialogOnLoad;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	protected void displayActivity() {
		setContentView(R.layout.activity_result);
	}

	@Override
	protected void initViews() {
		tvRatio = (TextView) findViewById(R.id.tvRatio);
		tvScore = (TextView) findViewById(R.id.tvScore);
		gridView = (GridView) findViewById(R.id.gridView1);
		float scalefactor = getResources().getDisplayMetrics().density * 100;
		int number = getWindowManager().getDefaultDisplay().getWidth();
		int columns = (int) ((float) number / (float) scalefactor);
		gridView.setNumColumns(columns);
	}

	@Override
	protected void initVariables() {
		jsonHandler = new StringJSONHandler();
	}

	@Override
	protected void initActions() {
		tvScore.setTextSize(TypedValue.COMPLEX_UNIT_PT, 14);
		tvRatio.setTextSize(TypedValue.COMPLEX_UNIT_PT, 14);
		userAnswers = this.getIntent().getExtras().getIntArray("user answers");
		ansIDs = this.getIntent().getExtras().getIntegerArrayList("answer IDs");
		String result = this.getIntent().getExtras().getString("result");
		Log.i("on_check", result);
		resultHolder = jsonHandler.doRrepareForUserResult(result, ansIDs,
				userAnswers);
		tvScore.setText("" + resultHolder.getMark());
		tvRatio.setText(resultHolder.getNum_correct() + "/"
				+ resultHolder.getHandledResult().size());
		resultAdapter = new ResultAdapter(this, resultHolder.getHandledResult());
		gridView.setAdapter(resultAdapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(getApplicationContext(),
						ExamActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				intent.putExtra("position", position + 1);
				intent.putExtra("correct answers",
						resultHolder.getCorrect_answers());
				intent.putExtra("ansFlags", resultHolder.getAnsFlags());
				startActivity(intent);
			}
		});
	}

	@Override
	protected void setUpActionBar() {
		super.setUpActionBar();
		getSupportActionBar().setDisplayShowHomeEnabled(false);
	}

	@Override
	public void onBackPressed() {
		showConfirmDialog();
	}

	private void showConfirmDialog() {
		AlertDialog.Builder restartAlertBuilder = new AlertDialog.Builder(this);
		restartAlertBuilder.setTitle("Warning");
		restartAlertBuilder
				.setMessage("This will back to the main screen, are you sure ?");
		restartAlertBuilder.setCancelable(false);
		restartAlertBuilder.setPositiveButton("Ok", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent i = new Intent(getBaseContext(),
						CategoriesActivity.class);
				i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(i);
			}
		});
		restartAlertBuilder.setNegativeButton("Nope", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});

		AlertDialog restartAlertDialog = restartAlertBuilder.create();
		restartAlertDialog.show();

	}

	public void onClickRetry(View view) {
		if (NetworkUtility.checkNetworkState(getBaseContext())){
			SOAPConnector connector = new SOAPConnector(RequestBuilder.BuildOnLoadRequest(getCurrentCategoryId(), getCurrentDifficultId()));
			connector.setOnResponseListener(this);
			progressDialogOnLoad = ProgressDialog.show(this, "Loading exam", "Please wait …");
			connector.startRequest();
		}
		else
			NetworkUtility.showTimeOutDialog(getActivityInstance());
	}

	public void onClickHome(View view) {
		Intent i = new Intent(getBaseContext(), CategoriesActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(i);
	}

	@Override
	public void onResponse(String jsonResponse) {
		progressDialogOnLoad.dismiss();
		  if(jsonHandler.checkError(jsonResponse)==false){ 
			  //Log.d("onLoad", jsonResponse.toString());
		   Intent intent = new Intent(this, ExamActivity.class);
		   intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		   intent.putExtra("title", getCurrentSubjectName() + "-" + getCurrentDiffName());
		   intent.putExtra("data", jsonResponse.toString());
		   startActivity(intent);
		  } else {
		   Toast.makeText(getApplicationContext(), jsonHandler.getErrorMessage(jsonResponse), Toast.LENGTH_LONG).show();
		  }
	}

	@Override
	public void onRequestTimeOut() {
		progressDialogOnLoad.dismiss();
		NetworkUtility.showTimeOutDialog(this);
	}
}
